import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/chat.dart';

class ChatRepository {
  static final ChatRepository _instance = ChatRepository._internal();
  factory ChatRepository() => _instance;
  ChatRepository._internal();

  // 发送聊天消息
  Future<int> sendMessage(Chat chat) async {
    final db = await DBHelper.database;
    return await db.insert('chat', chat.toMap());
  }

  // 获取两个用户之间的聊天记录
  Future<List<Chat>> getChatMessages(int userId1, int userId2) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'chat',
      where: '(sendUserId = ? AND acceptUserId = ?) OR (sendUserId = ? AND acceptUserId = ?)',
      whereArgs: [userId1, userId2, userId2, userId1],
      orderBy: 'sendTime ASC',
    );
    return res.map((map) => Chat.fromMap(map)).toList();
  }

  // 获取用户的所有聊天记录
  Future<List<Chat>> getAllChatsForUser(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'chat',
      where: 'sendUserId = ? OR acceptUserId = ?',
      whereArgs: [userId, userId],
      orderBy: 'sendTime DESC',
    );
    return res.map((map) => Chat.fromMap(map)).toList();
  }

  // 删除聊天消息
  Future<int> deleteMessage(int chatId) async {
    final db = await DBHelper.database;
    return await db.delete('chat', where: 'id = ?', whereArgs: [chatId]);
  }

  // 删除两个用户之间的所有聊天记录
  Future<int> deleteChatBetweenUsers(int userId1, int userId2) async {
    final db = await DBHelper.database;
    return await db.delete(
      'chat',
      where: '(sendUserId = ? AND acceptUserId = ?) OR (sendUserId = ? AND acceptUserId = ?)',
      whereArgs: [userId1, userId2, userId2, userId1],
    );
  }

  // 获取最新的聊天消息（用于聊天列表）
  Future<Chat?> getLatestMessageBetweenUsers(int userId1, int userId2) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'chat',
      where: '(sendUserId = ? AND acceptUserId = ?) OR (sendUserId = ? AND acceptUserId = ?)',
      whereArgs: [userId1, userId2, userId2, userId1],
      orderBy: 'sendTime DESC',
      limit: 1,
    );
    if (res.isNotEmpty) {
      return Chat.fromMap(res.first);
    }
    return null;
  }

  // 获取未读消息数量
  Future<int> getUnreadMessageCount(int currentUserId, int otherUserId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'chat',
      where: 'sendUserId = ? AND acceptUserId = ? AND isRead = 0',
      whereArgs: [otherUserId, currentUserId],
    );
    return res.length;
  }

  // 标记消息为已读
  Future<int> markMessagesAsRead(int currentUserId, int otherUserId) async {
    final db = await DBHelper.database;
    return await db.update(
      'chat',
      {'isRead': 1},
      where: 'sendUserId = ? AND acceptUserId = ? AND isRead = 0',
      whereArgs: [otherUserId, currentUserId],
    );
  }

  // 获取所有聊过天的用户及其未读消息数
  Future<Map<int, int>> getUnreadCountsForAllChats(int currentUserId) async {
    final db = await DBHelper.database;
    final res = await db.rawQuery('''
      SELECT sendUserId, COUNT(*) as unreadCount
      FROM chat
      WHERE acceptUserId = ? AND isRead = 0
      GROUP BY sendUserId
    ''', [currentUserId]);

    Map<int, int> unreadCounts = {};
    for (final row in res) {
      unreadCounts[row['sendUserId'] as int] = row['unreadCount'] as int;
    }
    return unreadCounts;
  }
}
